package so.sao.code.service.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;


public class FileUtils {

    /**
     * 对上传的文件进行处理
     * 
     * @param multiFile
     *            上传的文件
     * @param needRename
     *            上传的文件是否需要重新命名
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile multiFile, boolean needRename) throws IOException {
        String fileName = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        if (multiFile.getSize() > 0) {
            String shortName = multiFile.getOriginalFilename();

            inputStream = multiFile.getInputStream();

            // TODO need to upload file to Azure

            fileName = "uploadfilepath" + shortName;

            File file = new File("uploadfilepath" + fileName);
            outputStream = new FileOutputStream(file);

            int readBytes = 0;
            byte[] buffer = new byte[10000];
            while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }

            outputStream.close();
            inputStream.close();
        }

        return fileName;
    }

    /**
     * 对上传的文件做处理
     * 
     * @param absolutePath
     *            绝对路径
     * @param multiFile
     *            上传的文件
     * @param needRename
     *            上传是否要重命名
     * @return absolute file path. 'null' if multiFile was empty.
     */
    public static String writeFileToDisk(String absolutePath, MultipartFile multiFile) throws IOException {
        String fileName = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        if (multiFile.getSize() > 0) {
            String shortName = multiFile.getOriginalFilename();

            inputStream = multiFile.getInputStream();

            File folder = new File(absolutePath);
            if (!folder.exists()) {
                folder.mkdir();
            }

            if (!StringUtils.endsWith(absolutePath, File.separator)) {
                absolutePath += File.separator;
            }
            fileName = absolutePath + shortName;
   
            File file = new File(fileName);
            outputStream = new FileOutputStream(file);

            int readBytes = 0;
            byte[] buffer = new byte[10000];
            while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
           
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
        }

        return fileName;
    }

//    /**
//     * 根据当前时间和随机数对文件进行重命名
//     * 
//     * @param fileName
//     *            原文件名
//     * @return
//     */
//    public static String renameFileByRandom(String fileName) {
//        String formatDate = DateUtils.getCurrentGMT8LocalDateTime().toString("yyyyMMddHHmmss");
//        int random = new Random().nextInt(10000);
//        String filePrefix = new StringBuffer().append(formatDate).append(random).toString();
//
//        String newFileName = filePrefix + "." + StringUtils.substringAfterLast(fileName, ".");
//
//        return newFileName;
//    }

    /**
     * 
     * @Title: createTmpMarkFile
     * @Description: 创建临时文件，用于为文件加锁
     * @param fileName
     * @return 加锁成功返回true，失败返回false
     * @throws
     */
    public synchronized static boolean createTmpMarkFile(String fileName) {
        File markFile = new File(fileName);
        try {
            return markFile.createNewFile();
        } catch (IOException e) {
            return false;
        }
    }
    
    
    public static void main(String[] args) {
		System.out.println(Long.MAX_VALUE);
		System.out.println("9223372036854775807".length());
	}
    
    
    
    /**
     * 解压文件
     * 
     * @param zippedFile
     *            压缩文件绝对路径及文件名 d:/aa.zip
     * @param destFolder
     *            解压文件绝对路径 d:/或者d:/ab/
     * @return list 返回压缩文件中文件的名字集合
     * @throws IOException
     */
	public static List<String> unzips(String zippedFile, String destFolder)
			throws IOException {
		File zipFile = new File(zippedFile);
		File pathFile = new File(destFolder);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		ZipFile zip = null;
		try {
			List<String> list = new ArrayList<String>();
			zip = new ZipFile(zipFile, Charset.forName("GB2312"));
			for (Enumeration<?> entries = zip.entries(); entries
					.hasMoreElements();) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				String zipEntryName = entry.getName();
				list.add(destFolder + zipEntryName);
				InputStream in = zip.getInputStream(entry);
				String outPath = (destFolder + zipEntryName).replace('\\', '/');

                // 判断路径是否存在,不存在则创建文件路径
				File file = new File(outPath.substring(0,
						outPath.lastIndexOf('/')));
				if (!file.exists()) {
					file.mkdirs();
				}
                // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
				if (new File(outPath).isDirectory()) {
					continue;
				}

				OutputStream out = new FileOutputStream(outPath);
				byte[] buf1 = new byte[1024];
				int len;
				while ((len = in.read(buf1)) > 0) {
					out.write(buf1, 0, len);
				}
				in.close();
				out.close();
			}
			zip.close();
			return list;
		} finally {
			if (zip != null)
				zip.close();
		}
	}
}
